package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author L5775
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void save(Role role, Long[] ids) {
        //检查参数合法性
        //假设业务很复杂
        roleMapper.insert(role);
        if (ids != null && ids.length > 0){
            roleMapper.insertRelation(role.getId(),ids);
        }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteRelation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Role role, Long[] ids) {
        roleMapper.updateByPrimaryKey(role);
        roleMapper.deleteRelation(role.getId());
        if (ids != null && ids.length > 0) {
            roleMapper.insertRelation(role.getId(),ids);
        }
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult<Role> query(QueryObject qo) {
        int count = roleMapper.selectForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count, Collections.emptyList());
        }
        //判断当前页是否大于总页数
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize()
                : count / qo.getPageSize() + 1;
        if (qo.getCurrentPage()>totalPage){
            //如果大于就设置当前页为最后一页
            qo.setCurrentPage(totalPage);
        }

        List<Role> roles = roleMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count,roles);
    }


}
